import requests
import base64
from io import BytesIO
from PIL import Image

from tools._dectimer import timer


@timer()
def get_captcha():
    url = 'http://cgmgr.vrviu.com:19997/api/base/captcha'
    response = requests.post(url=url).json()
    data = response['data']['picPath']
    base64_str = data.split(",")[1]
    return base64_str


@timer()
def base64_to_image(base64_str, output_path='captcha.png'):
    image_data = base64.b64decode(base64_str)
    image = Image.open(BytesIO(image_data))
    image.save(output_path)
    return output_path


if __name__ == '__main__':
    base64_str = get_captcha()
    img_path = base64_to_image(base64_str)